﻿using System;
using System.Configuration;
using System.Linq;
using System.Web;
using Common.Logging;
using Newtonsoft.Json;
using OutDbContext;
using Senparc.Weixin;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.CommonAPIs;
using User.Api.BizExtensions;
using Senparc.Weixin.Entities;

namespace User.Api.Helpers
{
    public class MessageHelper
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof (MessageHelper));
        private static readonly string WxOauth2State = "GbkYin666";

        #region 模板消息参数
        //医院通知
        const string HospNoticeTempalteId = "gOfnsWQ2KBX9YKBTrpww0_Hd9nuZkFPVk3ZuvTI0pOM";

        const string TopColor = "#0000FF";

        const string FirstColor = "#173177";

        const string RemarkColor = "#173177";

        const string NoticeColor = "#173177";
        #endregion

        /// <summary>
        /// 获取网页地址
        /// </summary>
        /// <param name="routePath"></param>
        /// <returns></returns>
        public static string GetH5Url(string routePath)
        {
            var h5BaseAddress = ConfigurationManager.AppSettings["H5BaseAddress"];
            var baseAddress = ConfigurationManager.AppSettings["BaseAddress"];
            var appId = ConfigurationManager.AppSettings["WeixinAppId"];

            var url = h5BaseAddress + routePath;

            var oauth2Url = OAuthApi.GetAuthorizeUrl(appId,
                baseAddress
                + "api/Auth/WxOauth2?url="
                + HttpUtility.UrlEncode(url), WxOauth2State, OAuthScope.snsapi_userinfo);

            return oauth2Url;
        }

        /// <summary>
        /// 发送预约成功消息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        /// <returns></returns>
        public static void SendBookSucceedMsg(int orderId, int retryCount = 0)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var order = ctx.BookOrders.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return;
                }

                var url = GetH5Url("/index/search-book-info");
                var messageTS = $"请认真阅读，以免担误您的宝贵时间\r\n预检分诊流程：儿科患者持病历本至护士分诊台进行预检（无病历本患者先到客服处登记资料领取门诊条码），护士按患者情况给患者分级，患者进行预检后方能到挂号处按平诊急诊分级挂号，急诊患者按预检等级由高到低排队就诊";
                var message =
                    string.Format(
                        "您好，预约挂号成功！\r\n" +
                        "预约流水号：" + order.FlowNo + "\r\n" +
                        "预约医生：{0}\r\n" +
                        "预约日期：{1}\r\n" +
                        "<a href='{2}'>点这里【查看预约单】</a>",
                        order.DoctorName,
                        order.BookStartTime.Substring(0,10) + "  "+ order.BookStartTime.Substring(11, 5) + " - " + order.BookEndTime.Substring(11,5),
                        url);

                message += "\r\n温馨提示：\r\n请于" + order.BookStartTime.Substring(0, 16) + 
                    "提前20分钟凭流水号到挂号处报到并告知收费员是预约客户。若未能按时报到，则当次预约视为失约处理，当月若失约达到三次者将暂停当月的预约服务，下个月自动恢复，谢谢理解配合。";


                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                var openId = wxUser?.OpenId ?? "";
                try
                {
                    CustomApi.SendText(null, openId, message);
                    if (order.DeptName == "门诊儿科" || order.DeptName == "急诊科")
                    {
                        CustomApi.SendText(null, openId, messageTS);
                    }
                    
                }
                catch (ErrorJsonResultException ex)
                {
                    Logger.ErrorFormat("发送预约成功消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                    {
                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                        AccessTokenContainer.GetAccessTokenResult(appId, true);

                        if (retryCount <= 1)
                        {
                            retryCount++;
                            SendBookSucceedMsg(orderId, retryCount);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("发送预约成功消息时出错，信息：{0}", JsonConvert.SerializeObject(ex));
                }
            }
        }

        /// <summary>
        /// 发送取消预约成功消息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        /// <returns></returns>
        public static void SendCancellBookSucceedMsg(int orderId, int retryCount = 0)
        {
            try
            {

                using (var ctx = new FsssdqfybjyEntities())
                {
                    var order = ctx.BookOrders.FirstOrDefault(x => x.Id == orderId);
                    if (order == null)
                    {
                        return;
                    }

                    var message = "您的预约订单(预约流水号:" + order.FlowNo + ")已取消，感谢使用广东医科大学附属妇女儿童医院服务号";

                    var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                    var openId = wxUser?.OpenId ?? "";
                    try
                    {
                        CustomApi.SendText(null, openId, message);
                    }
                    catch (ErrorJsonResultException ex)
                    {
                        Logger.ErrorFormat("发送取消预约成功消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                        if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                            || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                        {
                            var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                            AccessTokenContainer.GetAccessTokenResult(appId, true);

                            if (retryCount <= 1)
                            {
                                retryCount++;
                                SendBookSucceedMsg(orderId, retryCount);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat("发送取消预约成功消息时出错，信息：{0}", JsonConvert.SerializeObject(ex));
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("Worker 线程发生错误3，信息：{0}", JsonConvert.SerializeObject(ex));
            }
        }

        /// <summary>
        /// 发送挂号成功消息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        /// <returns></returns>
        public static void SendRegSucceedMsg(int orderId, int retryCount = 0)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var order = ctx.ApptOrders.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return;
                }
                var message = "";
                var messageTS = $"请认真阅读，以免担误您的宝贵时间\r\n预检分诊流程：儿科患者持病历本至护士分诊台进行预检（无病历本患者先到客服处登记资料领取门诊条码），护士按患者情况给患者分级，患者进行预检后方能到挂号处按平诊急诊分级挂号，急诊患者按预检等级由高到低排队就诊";

                //var url = GetH5Url("/index/search-reg-info");
                //var message =
                //    string.Format(
                //        "挂号成功\r" +
                //        "订单号：" + order.OrderNo + "\r" +
                //        "姓名：{0}\r" +
                //        "诊疗号：{1}\r" +
                //        "科室：{2}\r" +
                //        "医生：{3}\r" +
                //        "就诊日期：{4}\r" +
                //        "挂号费用：{5} 元\r\n" +
                //        "<a href='{6}'>点这里【查看挂号单】</a>",
                //        order.CardName,
                //        order.CardNo,
                //        order.DeptName,
                //        order.DoctorName,
                //        order.RegDate,
                //        order.SumFee.GetValueOrDefault().ToString("F2"),
                //        url);

                
                if (order.OrderType == ApptOrderExtensions.OrderType.预约.ToInt32().ToString())
                {
                    message = $"报到成功！请您到{order.Location}候诊。\r\n您的排队号是：{order.WaitNo},等待人数：{order.WaitCount}。";
                }
                else
                {
                    message = $"挂号成功！您的候诊号为{order.WaitNo}，预计就诊时间{order.SuggestBeginTime}。\r\n请合理安排时间，未准时进诊患者将作顺延候诊处理，3次叫号均未准时进诊患者，需到分诊护士台重新分诊排队";
                }


                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                var openId = wxUser?.OpenId ?? "";
                try
                {
                    CustomApi.SendText(null, openId, message);
                    if (order.DeptName == "门诊儿科" || order.DeptName == "急诊科")
                    {
                        CustomApi.SendText(null, openId, messageTS);
                    }
                }
                catch (ErrorJsonResultException ex)
                {
                    Logger.ErrorFormat("发送挂号成功消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                    {
                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                        AccessTokenContainer.GetAccessTokenResult(appId, true);

                        if (retryCount <= 1)
                        {
                            retryCount++;
                            SendRegSucceedMsg(orderId, retryCount);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("发送挂号成功消息时出错，信息：{0}", JsonConvert.SerializeObject(ex));
                }
            }
        }

        /// <summary>
        /// 发送挂号失败消息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        public static void SendRegFailedMsg(int orderId, int retryCount = 0)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var order = ctx.ApptOrders.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return;
                }

                //var message =
                //    string.Format(
                //        "挂号失败！\r" +
                //        "订单号：" + order.OrderNo + "\r" +
                //        "姓名：{0}\r" +
                //        "诊疗号：{1}\r" +
                //        "科室：{2}\r" +
                //        "医生：{3}\r" +
                //        "就诊日期：{4}\r" +
                //        "挂号费用：{5} 元",
                //        order.CardName,
                //        order.CardNo,
                //        order.DeptName,
                //        order.DoctorName,
                //        order.RegDate,
                //        order.SumFee.GetValueOrDefault().ToString("F2"));

                var message = "";
                if (order.OrderType == ApptOrderExtensions.OrderType.预约.ToInt32().ToString())
                {
                    message = $"报到失败！失败原因：{order.Remark}";
                }
                else
                {
                    message = $"挂号失败！失败原因：{order.Remark}";
                }

                if (order.SumFee > 0)
                {
                    message += "\r\n系统正在执行退费操作，稍后您的所缴纳的款项将会退回您的账户中";
                }

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                var openId = wxUser?.OpenId ?? "";
                try
                {
                    CustomApi.SendText(null, openId, message);
                }
                catch (ErrorJsonResultException ex)
                {
                    Logger.ErrorFormat("发送挂号失败消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                    {
                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                        AccessTokenContainer.GetAccessTokenResult(appId, true);

                        if (retryCount <= 1)
                        {
                            retryCount++;
                            SendRegFailedMsg(orderId, retryCount);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("发送挂号失败消息时出错，信息：{0}", JsonConvert.SerializeObject(ex));
                }
            }
        }

        /// <summary>
        /// 发送挂号失败退费成功消息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        public static void SendRegFailedRefundSucceedMsg(int orderId, int retryCount = 0)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var order = ctx.ApptOrders.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return;
                }

                var message =
                    string.Format(
                        "退费成功！\r" +
                        "挂号单信息：\r" +
                        "订单号：" + order.OrderNo + "\r" +
                        "姓名：{0}\r" +
                        "诊疗号：{1}\r" +
                        "科室：{2}\r" +
                        "医生：{3}\r" +
                        "就诊日期：{4}\r" +
                        "挂号费用：{5} 元\r\n" +
                        "您所缴纳的款项已退回。微信零钱支付即刻到账，银行卡支付7个工作日内到账。请注意查收",
                        order.CardName,
                        order.CardNo,
                        order.DeptName,
                        order.DoctorName,
                        order.RegDate,
                        order.SumFee.GetValueOrDefault().ToString("F2"));

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                var openId = wxUser?.OpenId ?? "";
                try
                {
                    CustomApi.SendText(null, openId, message);
                }
                catch (ErrorJsonResultException ex)
                {
                    Logger.ErrorFormat("发送挂号失败退费成功消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                    {
                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                        AccessTokenContainer.GetAccessTokenResult(appId, true);

                        if (retryCount <= 1)
                        {
                            retryCount++;
                            SendRegFailedRefundSucceedMsg(orderId, retryCount);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("发送挂号失败退费成功消息时出错，信息：{0}", JsonConvert.SerializeObject(ex));
                }
            }
        }

        /// <summary>
        /// 发送退号成功消息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        public static void SendUnpickupSucceedMsg(int orderId, int retryCount = 0)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var order = ctx.ApptOrders.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return;
                }

                var message =
                    string.Format(
                        "退号成功！\r" +
                        "订单号：" + order.OrderNo + "\r" +
                        "姓名：{0}\r" +
                        "诊疗号：{1}\r" +
                        "科室：{2}\r" +
                        "医生：{3}\r" +
                        "就诊日期：{4}\r" +
                        "挂号费用：{5} 元",
                        order.CardName,
                        order.CardNo,
                        order.DeptName,
                        order.DoctorName,
                        order.RegDate,
                        order.SumFee.GetValueOrDefault().ToString("F2"));

                if (order.SumFee > 0)
                {
                    message += "\r\n系统正在执行退费操作，稍后您的所缴纳的款项将会退回您的账户中";
                }

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                var openId = wxUser?.OpenId ?? "";
                try
                {
                    CustomApi.SendText(null, openId, message);
                }
                catch (ErrorJsonResultException ex)
                {
                    Logger.ErrorFormat("发送退号成功消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                    {
                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                        AccessTokenContainer.GetAccessTokenResult(appId, true);

                        if (retryCount <= 1)
                        {
                            retryCount++;
                            SendUnpickupSucceedMsg(orderId, retryCount);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("发送退号成功消息时出错，信息：{0}", JsonConvert.SerializeObject(ex));
                }
            }
        }

        /// <summary>
        /// 发送退号失败消息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        /// <returns></returns>
        public static void SendUnpickupFailedMsg(int orderId, int retryCount = 0)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var order = ctx.ApptOrders.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return;
                }

                var url = GetH5Url("/index/reg-order-detail/" + order.Id);

                var message =
                    string.Format(
                        "退号失败！\r" +
                        "订单号：" + order.OrderNo + "\r" +
                        "姓名：{0}\r" +
                        "诊疗号：{1}\r" +
                        "科室：{2}\r" +
                        "医生：{3}\r" +
                        "就诊日期：{4}\r" +
                        "挂号费用：{5} 元\r\n" +
                        "<a href='{6}'>点这里【查看挂号单】</a>",
                        order.CardName,
                        order.CardNo,
                        order.DeptName,
                        order.DoctorName,
                        order.RegDate,
                        order.SumFee.GetValueOrDefault().ToString("F2"),
                        url);

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                var openId = wxUser?.OpenId ?? "";
                try
                {
                    CustomApi.SendText(null, openId, message);
                }
                catch (ErrorJsonResultException ex)
                {
                    Logger.ErrorFormat("发送退号失败消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                    {
                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                        AccessTokenContainer.GetAccessTokenResult(appId, true);

                        if (retryCount <= 1)
                        {
                            retryCount++;
                            SendUnpickupFailedMsg(orderId, retryCount);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("发送退号失败消息时出错，信息：{0}", JsonConvert.SerializeObject(ex));
                }
            }
        }

        /// <summary>
        /// 发送退号成功退费成功消息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        public static void SendUnpickupSucceedRefundSucceedMsg(int orderId, int retryCount = 0)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var order = ctx.ApptOrders.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return;
                }

                var message =
                    string.Format(
                        "退费成功！\r" +
                        "挂号单信息：\r" +
                        "订单号：" + order.OrderNo + "\r" +
                        "姓名：{0}\r" +
                        "诊疗号：{1}\r" +
                        "科室：{2}\r" +
                        "医生：{3}\r" +
                        "就诊日期：{4}\r" +
                        "挂号费用：{5} 元\r\n" +
                        "您所缴纳的款项已退回。微信零钱支付即刻到账，银行卡支付7个工作日内到账。请注意查收",
                        order.CardName,
                        order.CardNo,
                        order.DeptName,
                        order.DoctorName,
                        order.RegDate,
                        order.SumFee.GetValueOrDefault().ToString("F2"));

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                var openId = wxUser?.OpenId ?? "";
                try
                {
                    CustomApi.SendText(null, openId, message);
                }
                catch (ErrorJsonResultException ex)
                {
                    Logger.ErrorFormat("发送退号成功退费成功消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                    {
                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                        AccessTokenContainer.GetAccessTokenResult(appId, true);

                        if (retryCount <= 1)
                        {
                            retryCount++;
                            SendUnpickupSucceedRefundSucceedMsg(orderId, retryCount);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("发送退号成功退费成功消息出错，信息：{0}", JsonConvert.SerializeObject(ex));
                }
            }
        }

        /// <summary>
        /// 发送缴费成功通知
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        public static void SendBillSucceedMsg(int orderId, int retryCount = 0)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var order = ctx.ClinRecipeOrders.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return;
                }

                var url = GetH5Url("/index/bill-pay-list");

                var message =
                    string.Format("您已缴费成功！\r\n处方处理提示您：\r\n{0}\r\n<a href='{1}'>点这里可查询您的缴费记录</a>",
                        order.ResultMark, url);

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                var openId = wxUser?.OpenId ?? "";
                try
                {
                    CustomApi.SendText(null, openId, message);
                }
                catch (ErrorJsonResultException ex)
                {
                    Logger.ErrorFormat("发送缴费成功消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                    {
                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                        AccessTokenContainer.GetAccessTokenResult(appId, true);

                        if (retryCount <= 1)
                        {
                            retryCount++;
                            SendBillSucceedMsg(orderId, retryCount);
                            //return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("发送缴费成功消息时出错，信息：{0}", JsonConvert.SerializeObject(ex));
                }


                #region   发送问卷调查
                //                var card = ctx.HospCards.Where(x => x.CardNo == order.CardNo && x.RecStatus == 1).Select(
                //                    x => new {x.PatientName, x.CardNo, x.WxUserId}).FirstOrDefault();
                //                if (card == null)
                //                {
                //                    return;
                //                }
                //
                //                string patientName = card.PatientName;
                //                string cardNo = card.CardNo;
                //
                //                var paperUrl = GetH5Url("/index/paper-list");
                //                var strremark = "姓名:" + patientName + " 诊疗号:" + cardNo;
                //                var data = new
                //                {
                //                    first = new
                //                    {
                //                        value = strremark,
                //                        color = FirstColor
                //                    },
                //                    keyword1 = new
                //                    {
                //                        value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), //通知时间
                //                        color = NoticeColor
                //                    },
                //                    keyword2 = new
                //                    {
                //                        value = "您有新的调查问卷", //通知内容
                //                        color = NoticeColor
                //                    },
                //                    remark = new
                //                    {
                //                        value = "您还可以对本次就诊过程做评价。",
                //                        color = RemarkColor
                //                    }
                //                };
                //                try
                //                {
                //                    var result = SendTemplateMessage("满意度调查通知", strremark, null, openId, HospNoticeTempalteId, TopColor,
                //                        paperUrl, data);
                //                }
                //                catch (ErrorJsonResultException ex)
                //                {
                //                    Logger.ErrorFormat("发送满意度调查通知时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));
                //
                //                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                //                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                //                    {
                //                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                //                        AccessTokenContainer.GetAccessTokenResult(appId, true);
                //
                //
                //                        SendTemplateMessage("满意度调查通知", strremark, null, openId, HospNoticeTempalteId, TopColor,
                //                            paperUrl, data);
                //
                //                    }
                //                }
                //                catch (Exception ex)
                //                {
                //                    Logger.ErrorFormat("发送满意度调查通知出错，信息：{0}", JsonConvert.SerializeObject(ex));
                //                }
                #endregion
            }
        }

        /// <summary>
        /// 发送缴费失败通知
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        public static void SendBillFailedMsg(int orderId, int retryCount = 0)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var order = ctx.ClinRecipeOrders.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return;
                }

                var message =
                    string.Format(
                        "缴费失败！\r" +
                        "订单号：" + order.OrderNo + "\r" +
                        "姓名：{0}\r" +
                        "诊疗号：{1}\r" +
                        "本次缴费的处方编号：{2}\r" +
                        "失败原因：{3}",
                        order.PatName,
                        order.CardNo,
                        order.RecipeIds, 
                        order.Remark);

                message += "\r\n系统正在执行退费操作，稍后您的所缴纳的款项将会退回您的账户中";

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                var openId = wxUser?.OpenId ?? "";
                try
                {
                    CustomApi.SendText(null, openId, message);
                }
                catch (ErrorJsonResultException ex)
                {
                    Logger.ErrorFormat("发送缴费失败消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                    {
                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                        AccessTokenContainer.GetAccessTokenResult(appId, true);

                        if (retryCount <= 1)
                        {
                            retryCount++;
                            SendBillFailedMsg(orderId, retryCount);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("发送缴费失败消息时出错，信息：{0}", JsonConvert.SerializeObject(ex));
                }
            }
        }

        /// <summary>
        /// 发送缴费失败退费成功消息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        public static void SendBillFailedRefundSucceedMsg(int orderId, int retryCount = 0)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var order = ctx.ClinRecipeOrders.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return;
                }

                var message =
                    string.Format(
                        "退费成功！\r" +
                        "缴费单信息：\r" +
                        "订单号：" + order.OrderNo + "\r" +
                        "姓名：{0}\r" +
                        "诊疗号：{1}\r" +
                        "本次缴费的处方编号：{2}\r" +
                        "您所缴纳的款项已退回。微信零钱支付即刻到账，银行卡支付7个工作日内到账。请注意查收",
                        order.PatName,
                        order.CardNo,
                        order.RecipeIds);

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                var openId = wxUser?.OpenId ?? "";
                try
                {
                    CustomApi.SendText(null, openId, message);
                }
                catch (ErrorJsonResultException ex)
                {
                    Logger.ErrorFormat("发送缴费失败退费成功消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                    {
                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                        AccessTokenContainer.GetAccessTokenResult(appId, true);

                        if (retryCount <= 1)
                        {
                            retryCount++;
                            SendBillFailedRefundSucceedMsg(orderId, retryCount);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("发送缴费失败退费成功消息时出错，信息：{0}", JsonConvert.SerializeObject(ex));
                }
            }
        }

        /// <summary>
        /// 发送住院预缴金成功通知
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        public static void SendPrepaySucceedMsg(int orderId, int retryCount = 0)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var order = ctx.InpatientPrepayOrders.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return;
                }

                var url = GetH5Url("/index/search-prepay-info");

                var message =
                    string.Format(
                        "住院预缴金缴纳成功\r" +
                        "订单号：" + order.OrderNo + "\r" +
                        "姓名：{0}\r" +
                        "住院号：{1}\r" +
                        "充值金额：{2} 元\r\n" +
                        "<a href='{3}'>点这里【查看住院预缴单】</a>",
                        order.PatientName,
                        order.WardNo,
                        order.PrepayMoney.GetValueOrDefault().ToString("F2"),
                        url);

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                var openId = wxUser?.OpenId ?? "";
                try
                {
                    CustomApi.SendText(null, openId, message);
                }
                catch (ErrorJsonResultException ex)
                {
                    Logger.ErrorFormat("发送住院预缴金成功消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                    {
                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                        AccessTokenContainer.GetAccessTokenResult(appId, true);

                        if (retryCount <= 1)
                        {
                            retryCount++;
                            SendPrepaySucceedMsg(orderId, retryCount);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("发送住院预缴金成功消息时出错，信息：{0}", JsonConvert.SerializeObject(ex));
                }
            }
        }

        /// <summary>
        /// 发送住院预缴金失败通知
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        public static void SendPrepayFailedMsg(int orderId, int retryCount = 0)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var order = ctx.InpatientPrepayOrders.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return;
                }

                var message =
                    string.Format(
                        "住院预缴金缴纳失败！\r" +
                        "订单号：" + order.OrderNo + "\r" +
                        "姓名：{0}\r" +
                        "住院号：{1}\r" +
                        "充值金额：{2} 元\r",
                        order.PatientName,
                        order.WardNo,
                        order.PrepayMoney.GetValueOrDefault().ToString("F2"));

                message += "\r\n系统正在执行退费操作，稍后您的所缴纳的款项将会退回您的账户中";

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                var openId = wxUser?.OpenId ?? "";
                try
                {
                    CustomApi.SendText(null, openId, message);
                }
                catch (ErrorJsonResultException ex)
                {
                    Logger.ErrorFormat("发送住院预缴金失败消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                    {
                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                        AccessTokenContainer.GetAccessTokenResult(appId, true);

                        if (retryCount <= 1)
                        {
                            retryCount++;
                            SendPrepayFailedMsg(orderId, retryCount);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("发送住院预缴金失败消息时出错，信息：{0}", JsonConvert.SerializeObject(ex));
                }
            }
        }

        /// <summary>
        /// 发送住院预缴金失败退费成功消息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        public static void SendPrepayFailedRefundSucceedMsg(int orderId, int retryCount = 0)
        {
            using (var ctx = new FsssdqfybjyEntities())
            {
                var order = ctx.InpatientPrepayOrders.FirstOrDefault(x => x.Id == orderId);
                if (order == null)
                {
                    return;
                }

                var message =
                    string.Format(
                        "退费成功！\r" +
                        "住院预缴单信息：\r" +
                        "订单号：" + order.OrderNo + "\r" +
                        "姓名：{0}\r" +
                        "住院号：{1}\r" +
                        "充值金额：{2} 元\r\n" +
                        "您所缴纳的款项已退回。微信零钱支付即刻到账，银行卡支付7个工作日内到账。请注意查收",
                        order.PatientName,
                        order.WardNo,
                        order.PrepayMoney.GetValueOrDefault().ToString("F2"));

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == order.WxUserId);
                var openId = wxUser?.OpenId ?? "";
                try
                {
                    CustomApi.SendText(null, openId, message);
                }
                catch (ErrorJsonResultException ex)
                {
                    Logger.ErrorFormat("发送住院预缴金失败退费成功消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                    {
                        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                        AccessTokenContainer.GetAccessTokenResult(appId, true);

                        if (retryCount <= 1)
                        {
                            retryCount++;
                            SendPrepayFailedRefundSucceedMsg(orderId, retryCount);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("发送住院预缴金失败退费成功消息时出错，信息：{0}", JsonConvert.SerializeObject(ex));
                }
            }
        }

        /// <summary>
        /// 发送新缴费单消息
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="retryCount"></param>
        public static void SendNewBillMsg(int cardId, int retryCount = 0)
        {
            string patientName, cardNo, openId;
            using (var ctx = new FsssdqfybjyEntities())
            {
                var card = ctx.HospCards.Where(x => x.Id == cardId && x.RecStatus == 1).Select(
                    x => new { x.PatientName, x.CardNo, x.WxUserId }).FirstOrDefault();
                if (card == null)
                {
                    return;
                }

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == card.WxUserId && x.UnsubscribeDt == null);
                if (wxUser == null)
                {
                    return;
                }

                patientName = card.PatientName;
                cardNo = card.CardNo;
                openId = wxUser.OpenId;
            }

            var billUrl = GetH5Url("/index/get-bill");

            var strremark = "姓名:" + patientName + " 诊疗号:" + cardNo;

            var data = new
            {
                first = new
                {
                    value = "",
                    color = FirstColor
                },
                keyword1 = new
                {
                    value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),//通知时间
                    color = NoticeColor
                },

                keyword2 = new
                {
                    value = "您有新的缴费单（如果是免费孕检的请到人工窗口缴费）",//通知内容
                    color = NoticeColor
                },

                remark = new
                {
                    value = strremark,
                    color = RemarkColor
                }
            };

            try
            {

                var result = SendTemplateMessage("新缴费单通知", strremark, null, openId, HospNoticeTempalteId, TopColor, billUrl, data);

            }
            catch (ErrorJsonResultException ex)
            {
                Logger.ErrorFormat("发送新缴费单消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                {
                    var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                    AccessTokenContainer.GetAccessTokenResult(appId, true);

                    if (retryCount <= 1)
                    {
                        retryCount++;
                        SendNewBillMsg(cardId, retryCount);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("发送新缴费单消息出错，信息：{0}", JsonConvert.SerializeObject(ex));
            }
        }


        /// <summary>
        /// 发送新检验单消息
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="retryCount"></param>
        public static void SendNewInspectionMsg(int cardId, int retryCount = 0)
        {
            string patientName, cardNo, openId;
            using (var ctx = new FsssdqfybjyEntities())
            {
                var card = ctx.HospCards.Where(x => x.Id == cardId && x.RecStatus == 1).Select(
                    x => new { x.PatientName, x.CardNo, x.WxUserId }).FirstOrDefault();
                if (card == null)
                {
                    return;
                }

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == card.WxUserId && x.UnsubscribeDt == null);
                if (wxUser == null)
                {
                    return;
                }

                patientName = card.PatientName;
                cardNo = card.CardNo;
                openId = wxUser.OpenId;
            }

            var url = GetH5Url("/index/get-inspection");

            var strremark = "姓名:" + patientName + " 诊疗号:" + cardNo;
            var data = new
            {
                first = new
                {
                    value = "",
                    color = FirstColor
                },
                keyword1 = new
                {
                    value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), //通知时间
                    color = NoticeColor
                },

                keyword2 = new
                {
                    value = "您有新的检验单", //通知内容
                    color = NoticeColor
                },

                remark = new
                {
                    value = strremark,
                    color = RemarkColor
                }
            };
            try
            {
                var result = SendTemplateMessage("新检验单通知", strremark, null, openId, HospNoticeTempalteId, TopColor, url,
                    data);
            }
            catch (ErrorJsonResultException ex)
            {
                Logger.ErrorFormat("发送新检验单消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                    || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                {
                    var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                    AccessTokenContainer.GetAccessTokenResult(appId, true);

                    if (retryCount <= 1)
                    {
                        retryCount++;
                        SendNewInspectionMsg(cardId, retryCount);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("发送新检验单消息出错，信息：{0}", JsonConvert.SerializeObject(ex));
            }
        }

        /// <summary>
        /// 发送新检查单消息
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="retryCount"></param>
        public static void SendNewCheckMsg(int cardId, int retryCount = 0)
        {
            string patientName, cardNo, openId;
            using (var ctx = new FsssdqfybjyEntities())
            {
                var card = ctx.HospCards.Where(x => x.Id == cardId && x.RecStatus == 1).Select(
                    x => new { x.PatientName, x.CardNo, x.WxUserId }).FirstOrDefault();
                if (card == null)
                {
                    return;
                }

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == card.WxUserId && x.UnsubscribeDt == null);
                if (wxUser == null)
                {
                    return;
                }

                patientName = card.PatientName;
                cardNo = card.CardNo;
                openId = wxUser.OpenId;
            }

            var url = GetH5Url("/index/get-check");

            var strremark = "姓名:" + patientName + " 诊疗号:" + cardNo;
            var data = new
            {
                first = new
                {
                    value = "",
                    color = FirstColor
                },
                keyword1 = new
                {
                    value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), //通知时间
                    color = NoticeColor
                },

                keyword2 = new
                {
                    value = "您有新的检查单", //通知内容
                    color = NoticeColor
                },

                remark = new
                {
                    value = strremark,
                    color = RemarkColor
                }
            };
            try
            {
                var result = SendTemplateMessage("新检查单通知", strremark, null, openId, HospNoticeTempalteId, TopColor, url,
                    data);
            }
            catch (ErrorJsonResultException ex)
            {
                Logger.ErrorFormat("发送新检查单消息时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                    || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                {
                    var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                    AccessTokenContainer.GetAccessTokenResult(appId, true);

                    if (retryCount <= 1)
                    {
                        retryCount++;
                        SendNewCheckMsg(cardId, retryCount);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("发送新检查单消息出错，信息：{0}", JsonConvert.SerializeObject(ex));
            }
        }

        /// <summary>
        /// 发送新调查问卷消息
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="retryCount"></param>
        public static void SendNewPaperMsg(int cardId, int retryCount = 0)
        {
            string patientName, cardNo, openId;
            using (var ctx = new FsssdqfybjyEntities())
            {
                var card = ctx.HospCards.Where(x => x.Id == cardId && x.RecStatus == 1).Select(
                    x => new { x.PatientName, x.CardNo, x.WxUserId }).FirstOrDefault();
                if (card == null)
                {
                    return;
                }

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == card.WxUserId && x.UnsubscribeDt == null);
                if (wxUser == null)
                {
                    return;
                }

                patientName = card.PatientName;
                cardNo = card.CardNo;
                openId = wxUser.OpenId;
            }

            var paperUrl = GetH5Url("/index/paper-list");
            var strremark = "姓名:" + patientName + " 诊疗号:" + cardNo;
            var data = new
            {
                first = new
                {
                    value = strremark,
                    color = FirstColor
                },
                keyword1 = new
                {
                    value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), //通知时间
                    color = NoticeColor
                },
                keyword2 = new
                {
                    value = "您有新的调查问卷", //通知内容
                    color = NoticeColor
                },
                remark = new
                {
                    value = "您还可以对本次就诊过程做评价。",
                    color = RemarkColor
                }
            };
            try
            {
                var result = SendTemplateMessage("满意度调查通知", strremark, null, openId, HospNoticeTempalteId, TopColor,
                    paperUrl, data);
            }
            catch (ErrorJsonResultException ex)
            {
                Logger.ErrorFormat("发送满意度调查通知时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                    || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                {
                    var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                    AccessTokenContainer.GetAccessTokenResult(appId, true);

                    if (retryCount <= 1)
                    {
                        retryCount++;
                        SendNewPaperMsg(cardId, retryCount);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("发送满意度调查通知出错，信息：{0}", JsonConvert.SerializeObject(ex));
            }
        }

        /// <summary>
        /// 发送候诊队列消息
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="waitNo"></param>
        /// <param name="deptName"></param>
        /// <param name="doctorName"></param>
        /// <param name="retryCount"></param>
        public static void SendQueueMsg(int cardId, string waitNo, string deptName, string doctorName, int retryCount = 0)
        {
            string patientName, cardNo, openId;
            using (var ctx = new FsssdqfybjyEntities())
            {
                var card = ctx.HospCards.Where(x => x.Id == cardId && x.RecStatus == 1).Select(
                    x => new { x.PatientName, x.CardNo, x.WxUserId }).FirstOrDefault();
                if (card == null)
                {
                    return;
                }

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == card.WxUserId && x.UnsubscribeDt == null);
                if (wxUser == null)
                {
                    return;
                }

                patientName = card.PatientName;
                cardNo = card.CardNo;
                openId = wxUser.OpenId;
            }

            var url = GetH5Url("/index/get-queue");
            var strremark = "姓名:" + patientName + " 诊疗号:" + cardNo;
            var data = new
            {
                first = new
                {
                    value = strremark,
                    color = FirstColor
                },
                keyword1 = new
                {
                    value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), //通知时间
                    color = NoticeColor
                },
                keyword2 = new
                {
                    value = $"您前面还有 {waitNo} 个人在等待。",//通知内容
                    color = NoticeColor
                },
                remark = new
                {
                    value = $"科室：{deptName}   医生：{doctorName}",
                    color = RemarkColor
                }
            };
            try
            {
                var result = SendTemplateMessage("候诊队列通知", strremark, null, openId, HospNoticeTempalteId, TopColor,
                    url, data);
            }
            catch (ErrorJsonResultException ex)
            {
                Logger.ErrorFormat("发送候诊队列通知时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                    || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                {
                    var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                    AccessTokenContainer.GetAccessTokenResult(appId, true);

                    if (retryCount <= 1)
                    {
                        retryCount++;
                        SendQueueMsg(cardId, waitNo, deptName, doctorName, retryCount);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("发送候诊队列通知出错，信息：{0}", JsonConvert.SerializeObject(ex));
            }
        }


        /// <summary>
        /// 发送过号提醒消息
        /// </summary>
        /// <param name="cardId"></param>
        /// <param name="retryCount"></param>
        public static void SendOverQueueMsg(int cardId, int retryCount = 0)
        {
            string patientName, cardNo, openId;
            using (var ctx = new FsssdqfybjyEntities())
            {
                var card = ctx.HospCards.Where(x => x.Id == cardId && x.RecStatus == 1).Select(
                    x => new { x.PatientName, x.CardNo, x.WxUserId }).FirstOrDefault();
                if (card == null)
                {
                    return;
                }

                var wxUser = ctx.WxUsers.FirstOrDefault(x => x.Id == card.WxUserId && x.UnsubscribeDt == null);
                if (wxUser == null)
                {
                    return;
                }

                patientName = card.PatientName;
                cardNo = card.CardNo;
                openId = wxUser.OpenId;
            }

            var url = GetH5Url("/index/get-queue");
            var strremark = "姓名:" + patientName + " 诊疗号:" + cardNo;
            var data = new
            {
                first = new
                {
                    value = strremark,
                    color = FirstColor
                },
                keyword1 = new
                {
                    value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), //通知时间
                    color = NoticeColor
                },
                keyword2 = new
                {
                    value = "您已经被叫号，请马上进诊，谢谢合作", //通知内容
                    color = NoticeColor
                },
                remark = new
                {
                    value = "",
                    color = RemarkColor
                }
            };
            try
            {
                var result = SendTemplateMessage("候诊队列过号提醒通知", strremark, null, openId, HospNoticeTempalteId, TopColor,
                    url, data);
            }
            catch (ErrorJsonResultException ex)
            {
                Logger.ErrorFormat("发送候诊队列过号提醒通知时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

                if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
                    || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
                {
                    var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                    AccessTokenContainer.GetAccessTokenResult(appId, true);

                    if (retryCount <= 1)
                    {
                        retryCount++;
                        SendOverQueueMsg(cardId, retryCount);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("发送候诊队列过号提醒通知出错，信息：{0}", JsonConvert.SerializeObject(ex));
            }
        }

        /// <summary>
        /// 发送停诊通知
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="retryCount"></param>
        public static void SendHaltMsg(int orderId, int retryCount = 0)
        {
            //string openId, deptName, doctorName, regDate, orderType, startTime, endTime;
            //using (var ctx = new FsssdqfybjyEntities())
            //{
            //    var order = ctx.ApptOrders.Where(x => x.Id == orderId).Select
            //        (
            //            x => new
            //            {
            //                x.OpenId,
            //                x.DeptName,
            //                x.DoctorName,
            //                x.RegDate,
            //                x.OrderType,
            //                x.StartTime,
            //                x.EndTime
            //            }
            //        ).FirstOrDefault();
            //    if (order == null)
            //    {
            //        return;
            //    }
            //    openId = order.OpenId ?? "";
            //    deptName = order.DeptName ?? "";
            //    doctorName = order.DoctorName ?? "";
            //    regDate = order.RegDate ?? "";
            //    orderType = order.OrderType ?? "";
            //    startTime = order.StartTime ?? "";
            //    endTime = order.EndTime ?? "";
            //}
            //var url = GetH5Url("/index/reg-order-detail/" + orderId);

            //var templateId = "BY9yqF9YKi8kMc21_sjZLraODeqxD0298Pb-BOqtiB4";
            //var data = new
            //{
            //    first = new
            //    {
            //        value = "停诊详情如下：",
            //        color = "#173177"
            //    },
            //    hospitalname = new
            //    {
            //        value = "广东省妇幼保健院",
            //        color = "#173177"
            //    },

            //    deptname = new
            //    {
            //        value = deptName,
            //        color = "#173177"
            //    },
            //    doctorname = new
            //    {
            //        value = doctorName,
            //        color = "#173177"
            //    },
            //    planstarttime = new
            //    {
            //        value = (regDate + (orderType == "2" ? startTime + "-" + endTime : startTime)) ?? "",
            //        color = "#173177"
            //    },
            //    remark = new
            //    {
            //        value = "请您退号后，尽快预约其他医生。",
            //        color = "#173177"
            //    }
            //};


            //try
            //{
            //    var result = SendTemplateMessage("停诊通知", orderId.ToString(), null, openId, templateId, TopColor, url,
            //        data);
            //}
            //catch (ErrorJsonResultException ex)
            //{
            //    Logger.ErrorFormat("发送停诊通知时 Separc Weixin SDK 出错，信息：{0}", JsonConvert.SerializeObject(ex));

            //    if (ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效
            //        || ex.JsonResult.errcode == ReturnCode.不合法的access_token)
            //    {
            //        var appId = AccessTokenContainer.GetFirstOrDefaultAppId();
            //        AccessTokenContainer.GetAccessTokenResult(appId, true);

            //        if (retryCount <= 1)
            //        {
            //            retryCount++;
            //            SendHaltMsg(orderId, retryCount);
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Logger.ErrorFormat("发送停诊通知出错，信息：{0}", JsonConvert.SerializeObject(ex));
            //}
        }


        public static SendTemplateMessageResult SendTemplateMessage(string destination, string sendContent, string accessTokenOrAppId, string openId, string templateId, string topcolor, string url, object data, int timeOut = 10000)
        {
            var result = TemplateApi.SendTemplateMessage(null, openId, templateId, TopColor, url, data);
            try
            {
                using (var msgctx = new FsssdqfybjyEntities())
                {
                    var msglog = new MsgNotifyRecord()
                    {
                        Destination = destination,
                        SendContent = sendContent + " , openId:" + openId,

                        ReturnMessage = result.errcode.ToStringOrDefault(),
                        SendTime = DateTime.Now,

                    };
                    msgctx.MsgNotifyRecords.Add(msglog);
                    msgctx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("保存MsgNotifyRecord出错，信息：{0}", JsonConvert.SerializeObject(ex));
            }
            return result;
        }
    }
}